package com.wanxi.controller;

import com.alibaba.fastjson.JSONObject;
import com.wanxi.dto.ImgDTO;
import com.wanxi.dto.ResultDTO;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.RequestWrapper;
import java.io.*;
import java.nio.file.Paths;
import java.util.List;
@RestController
public class UploadServlet{
    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload";

    /**
     * 上传数据及保存文件
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @PostMapping("/upload")
    protected ResultDTO upload(@RequestParam("file")MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ResultDTO resultDTO = null;
        // 检测是否为多媒体上传
        if (multipartFile == null && multipartFile.isEmpty()) {
            resultDTO = ResultDTO.getResult("Error: 表单必须包含 enctype=multipart/form-data");
            return resultDTO;
        }
        //1，获取原始文件名
        String originalFilename = multipartFile.getOriginalFilename();
        //2,截取源文件的文件名前缀,不带后缀
        String fileNamePrefix = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        //3,加工处理文件名，原文件加上时间戳
        String newFileNamePrefix = fileNamePrefix + System.currentTimeMillis();
        //4,得到新文件名
        String newFileName = newFileNamePrefix + originalFilename.substring(originalFilename.lastIndexOf("."));

        // 构造临时路径来存储上传的文件
        // 这个路径相对当前应用的目录
        String uploadPath = request.getServletContext().getRealPath("./") + "/" + UPLOAD_DIRECTORY;
        createDirectory(uploadPath);
        try {
        //文件保存的绝对路径
        String filePath = uploadPath + "/" + newFileName;

        File storeFile = new File(filePath);
        multipartFile.transferTo(storeFile);

        // 在控制台输出文件的上传路径
        System.out.println(filePath);
        // 拷贝一份文件到web目录下
//        String path = storeFile.getPath().split("out")[0] + "/web/" + UPLOAD_DIRECTORY + "/";
        copyFile(storeFile, newFileName);

//        resultDTO = ResultDTO.getResult("", 1, new ImgDTO("/" + UPLOAD_DIRECTORY + "/" + newFileName));
        resultDTO = ResultDTO.getResult("上传成功", 1,new ImgDTO("/" + UPLOAD_DIRECTORY + "/" + newFileName));
        } catch (Exception ex) {
            request.setAttribute("message",
                    "错误信息: " + ex.getMessage());
        }
        return resultDTO;
    }
    private void createDirectory(String uploadPath) {
        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
    }

    private void copyFile(File storeFile, String fileName) {
        String path = storeFile.getPath().split("out")[0] + "/web/" + UPLOAD_DIRECTORY;
        createDirectory(path);
        File file = new File(path, fileName);
        try (InputStream inputStream = new FileInputStream(storeFile);
             OutputStream outputStream = new FileOutputStream(file);) {
            int read = 0;
            while ((read = inputStream.read()) != -1) {
                outputStream.write(read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

